import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

const incrApi = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.floor(Math.random() * 10 + 1))
    }, 1500);
  })
}

export const incrAsyncThunk =  createAsyncThunk(
  'myCounterAsync',
  async () => {
    const amount = await incrApi()
    return {amount}
  }
)

const myCounterSlice = createSlice({
  name: 'myCounter',
  initialState: {value: 0, status: 'idle'},
  reducers: {
    incr(state) { // +1
      state.value += 1
    },
    decr(state) { // -1
      state.value -= 1
    },
    incrByAmount(state, {payload: amount}) {
      state.value += amount
    }
  },
  extraReducers : {
    [incrAsyncThunk.pending](state) {
      state.status = 'pending'
    },
    [incrAsyncThunk.fulfilled](state, {payload}) {
      state.status = 'idle'
      state.value += payload.amount
    },
    [incrAsyncThunk.rejected](state) {
      state.status = 'error'
    },
  }
})
export default myCounterSlice.reducer
export const {incr, decr, incrByAmount} = myCounterSlice.actions

export const incrByAmountIfOdd = (amount) =>
  (dispatch, getState) =>{
  if (getState().myCounter.value % 2 === 1) {
    dispatch(incrByAmount(amount))
  }
}